package com.jmp.security.grant.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import one.stand.advice.ResultEnum;
import one.stand.dto.WechatLoginDto;
import one.stand.dto.WechatUserInfoDto;
import one.stand.util.AssertUtil;
import one.stand.util.HttpUtil2;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class WxLoginServiceImpl implements WxLoginService {
    /**
     * 小程序登录验证
     */
    private static final String url = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String url_oauth2 = "https://api.weixin.qq.com/sns/oauth2/access_token";


    @Override
    public WechatLoginDto code2accessToken(String code, String appId, String secret) {
        //封装需要的参数信息
        Map<String, String> requestUrlParam = new HashMap<>(4);
        //开发者设置中的appId
        requestUrlParam.put("appid", appId);
        //开发者设置中的appSecret
        requestUrlParam.put("secret", secret);
        //小程序调用wx.login返回的code
        requestUrlParam.put("js_code", code);
        //默认参数
        requestUrlParam.put("grant_type", "authorization_code");
//        JSONObject jsonObject = JSON.parseObject(HttpUtil.sendPost(urlConfig.getWxLogin(), requestUrlParam));
        JSONObject jsonObject = JSON.parseObject(HttpUtil2.post(url, requestUrlParam));
        log.info("微信登陆返回内容：{}", jsonObject);
        String errCode = jsonObject.getString("errcode");
        AssertUtil.isNull(errCode, ResultEnum.FAIL_LOGIN_WX);

        String openId = jsonObject.getString("openid");
        AssertUtil.nonNull(openId, "获取openId失败");
        String sessionKey = jsonObject.getString("session_key");
        String unionId = jsonObject.getString("unionid");
        return WechatLoginDto.builder()
                .openId(openId)
                .sessionKey(sessionKey)
                .unionId(unionId)
                .build();
    }

    @Override
    public WechatLoginDto loginBack(String code, String appId, String appSecret) {
        Map<String, String> param = new HashMap<>(4);
        param.put("code", code);
        param.put("appid", appId);
        param.put("secret", appSecret);
        param.put("grant_type", "authorization_code");
        String res = HttpUtil2.post(url_oauth2, param);
        log.info("获取到用户登陆信息：{}", res);
        JSONObject jsonObject = JSONObject.parseObject(res);
        String accessToken = jsonObject.getString("access_token");
        String unionid = jsonObject.getString("unionid");
        String openid = jsonObject.getString("openid");
        AssertUtil.nonNull(unionid, ResultEnum.FAIL_LOGIN_WX);
        return WechatLoginDto.builder()
                .accessToken(accessToken)
                .unionId(unionid)
                .openId(openid)
                .build();
    }

    /**
     * 解密用户敏感数据获取用户信息
     *
     * @param sessionKey    数据进行加密签名的密钥
     * @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
     * @param iv            加密算法的初始向量
     * @return
     * @author zhy
     */
    public WechatUserInfoDto getUserInfo(String encryptedData, String sessionKey, String iv) {
        try {
            String result = decrypt(encryptedData, sessionKey, iv);
            JSONObject jsonObject = JSON.parseObject(result);
            return WechatUserInfoDto.builder()
                    .avatarUrl(jsonObject.getString("avatarUrl"))
                    .nickName(jsonObject.getString("nickName"))
                    .gender(jsonObject.getInteger("gender"))
                    .country(jsonObject.getString("country"))
                    .province(jsonObject.getString("province"))
                    .city(jsonObject.getString("city"))
                    .unionid(jsonObject.getString("unionId"))
                    .purePhoneNumber(jsonObject.getString("purePhoneNumber"))
                    .build();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new OneLoginWxErrorException();
        }
    }

    @Override
    public WechatUserInfoDto getUserInfo(String accessToken, String openId) {
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        try {
            String result = HttpUtil2.get(url);
            JSONObject jsonObject = JSONObject.parseObject(result);
            return WechatUserInfoDto.builder()
                    .avatarUrl(jsonObject.getString("headimgurl"))
                    .nickName(jsonObject.getString("nickname"))
                    .gender(jsonObject.getInteger("sex"))
                    .country(jsonObject.getString("country"))
                    .province(jsonObject.getString("province"))
                    .city(jsonObject.getString("city"))
                    .unionid(jsonObject.getString("unionid"))
                    .build();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    private String decrypt(String encryptedData, String sessionKey, String iv) throws Exception {
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);

        // 如果密钥不足16位，那么就补足. 这个if 中的内容很重要
        int base = 16;
        if (keyByte.length % base != 0) {
            int groups = keyByte.length / base
                    + (keyByte.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
            keyByte = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
        parameters.init(new IvParameterSpec(ivByte));
        // 初始化
        cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
        byte[] resultByte = cipher.doFinal(dataByte);
        if (null != resultByte && resultByte.length > 0) {
            return new String(resultByte, StandardCharsets.UTF_8);
        }
        return null;
    }
}
